package server.utils;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class WebResourceUtils {

    public static Set<URL> loadClassPathUrls(File parent) throws MalformedURLException {
        Set<URL> urlList = new HashSet<>();
        if(!parent.exists()){
            return urlList;
        }
        File[] files = parent.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.isDirectory()){
                    return true;
                }
                String fileName = pathname.getName().toLowerCase();
                return fileName.endsWith(".class") || fileName.endsWith(".jar");
            }
        });
        if(files.length<=0){
            return urlList;
        }
        for(File file:files){
            String fileName = file.getName().toLowerCase();
            if(file.isDirectory()){
                urlList.addAll(loadClassPathUrls(file));
            }else if(fileName.endsWith("jar")){
                urlList.add(file.toURI().toURL());
            }else{
                urlList.add(file.getParentFile().toURI().toURL());
            }
        }
        return urlList;
    }
}
